package com.tinysand.advert.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

/**
 * Zuul请求的前置过滤器，记录请求的开始时间
 *
 * Created By TINY
 * Create Time 2020/2/14
 **/
@Slf4j
@Component // 标识为Spring组件
public class PreRequestFilter extends ZuulFilter {

    /* 分别对应Zuul中的四种过滤器类型：pre、route、post，error */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /* 值越小，表示优先级越高 */
    @Override
    public int filterOrder() {
        return 0;
    }

    /* 表示是否要执行这个过滤器，表现为是否调用 run 方法 */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /* 执行业务逻辑 */
    @Override
    @SuppressWarnings("all")
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        ctx.set("startTime", System.currentTimeMillis());

        return null;
    }
}
